package ltd.followkba;

import android.content.Intent;
import android.os.Bundle;

import com.kcbsdk.EventHandler;
import com.kcbsdk.cjmkcs;

import java.util.Timer;
import java.util.TimerTask;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.VARIA;
import ltd.advskin.base.KcAdvs;
import ltd.advskin.base.KcListAdapter;
import ltd.advskin.base.MPAGE;
import ltd.advskin.base.SkinActivity;
import ltd.advskin.permission.PermissionsActivity;
import ltd.advskin.task.MessageDbs;
import ltd.advskin.task.TaskRemoteServer;
import ltd.advskin.task.TaskSysUpdate;
import ltd.advskin.utils.AdvView;

import ltd.followkba.page.AddTaskPage;
import ltd.followkba.page.LocalPhotoPage;
import ltd.followkba.page.LoginManagePage;
import ltd.followkba.page.ModifyUserPage;
import ltd.followkba.page.OperationPage;
import ltd.followkba.page.PhotoWorksPage;
import ltd.followkba.page.RankListPage;
import ltd.followkba.page.RunStatePage;
import ltd.followkba.page.LoginTaskPage;
import ltd.followkba.page.SelectUserPage;
import ltd.followkba.page.SendToPage;
import ltd.followkba.page.TipsPage;
import ltd.followkba.page.UploadListPage;
import ltd.followkba.task.App33;
import ltd.followkba.page.DoneLogPage;
import ltd.followkba.page.EditTaskPage;
import ltd.followkba.page.EditUploadPage;
import ltd.followkba.task.App39;
import ltd.followkba.task.EditUtils;
import ltd.followkba.task.RunUtils;
import ltd.followkba.page.SearchUserPage;
import ltd.followkba.task.TaskService;
import ltd.followkba.page.UserHomePage;

import ltd.obbphoto.MOBBW;
import ltd.obbphoto.release.UploadWorksTask;
import main.MAPI;

import static com.kcbsdk.wpapper.*;
import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static main.MAPI.mMyTools;
import static main.MAPI.mMyUtils;


public class MainActivity extends SkinActivity {
    private long mBackPressedTime;
    private Timer mTimer;
    private byte g2Second;
    private int gUserID;
    private byte gMinute;
    private long gSecond;
    private boolean isStertPage;

    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        MSTRING(MAPI.GET_LOG_NAME(this) + text);
    }

    private void enableLog(){
        logEnable = true;
        RunUtils.logEnable = true;
        RunStatePage.logEnable = true;
        EditTaskPage.logEnable = true;
        LoginTaskPage.logEnable = true;
        EditUploadPage.logEnable = true;
        SearchUserPage.logEnable = true;
        UserHomePage.logEnable = true;
        RankListPage.logEnable = true;
        TaskService.logEnable = true;
        DoneLogPage.logEnable = true;
        LoginManagePage.logEnable = true;
        ModifyUserPage.logEnable = true;
        PhotoWorksPage.logEnable = true;
        LocalPhotoPage.logEnable = true;
        AddTaskPage.logEnable = true;
        UploadWorksTask.logEnable = true;
        SelectUserPage.logEnable = true;
        EditUtils.logEnable = true;
//        TaskApp3f.logEnable = true;
        UploadListPage.logEnable = true;
        TipsPage.logEnable = true;
        OperationPage.logEnable = true;
//        TaskDownload.logEnable = true;
//        SysBitmap.logEnable = true;
//        KcBtnImage.logEnable = true;
//        KcBannerView.logEnable = true;
//        KcBtnText.logEnable = true;
//        KcBtnImage.logEnable = true;
//        KcBtnUnion.logEnable = true;
//        KcBtnProgress.logEnable = true;
//        KcBtnMutil.logEnable = true;
//        KcBtnStyle.logEnable = true;
        SendToPage.logEnable = true;
        KcListAdapter.logEnable = true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page);
        MRAM.mActivity = this;
        MRAM.mContext = this;

        enableLog();
        AdvView.checkHorizontal();
        isStertPage = true;
        if (mTimer == null) {           // 第一次打开

            mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            onTimer();
                        }
                    });
                }
            }, 300, 300);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MLOG(String.format("cnkc PageActivity %02x %s %s" , requestCode, resultCode, data));
        if (requestCode == 0x99) {                  // 权限申请
            if (PermissionsActivity.PERMISSIONS_DENIED == resultCode) {             // 权限未被授予，退出应用
                if (VARIA.mSaveKcListener != null) {
                    VARIA.mSaveKcListener.onMessage(PermissionsActivity.PERMISSIONS_DENIED);
                }
            } else if (PermissionsActivity.PERMISSIONS_GRANTED == resultCode) {     // 权限被授予
                if (VARIA.mSaveKcListener != null){
                    VARIA.mSaveKcListener.onMessage(null);
                }
            }
            VARIA.mSaveKcListener = null;
        }
        initData();
        if (requestCode == 0x99) {                  // 权限申请
            if (PermissionsActivity.PERMISSIONS_DENIED == resultCode) {             // 权限未被授予，退出应用
                if (VARIA.mSaveKcListener != null) {
                    VARIA.mSaveKcListener.onMessage(PermissionsActivity.PERMISSIONS_DENIED);
                }
            } else if (PermissionsActivity.PERMISSIONS_GRANTED == resultCode) {     // 权限被授予
                if (VARIA.mSaveKcListener != null){
                    VARIA.mSaveKcListener.onMessage(null);
                }
            }
            VARIA.mSaveKcListener = null;
        }
    }

    @Override
    public void onBackPressed() {
        MLOG("PageActivity onBackPressed A \n"+ MPAGE.getBasePageTips());
        if ((MPAGE.mPageCurrent instanceof MainPage)){
            MLOG("PageActivity onBackPressed B "+mBackPressedTime);
            if (mBackPressedTime == 0 || ((System.currentTimeMillis() - mBackPressedTime) > 2000)) {
                mBackPressedTime = System.currentTimeMillis();
                MTOAST(getString(R.string.tip_back_pressed));
            } else {
                if ((System.currentTimeMillis() - mBackPressedTime) < 2000) {
                    if (mTimer != null){
                        mTimer .cancel();
                        mTimer = null;
                    }
                    MAPP.threadStop = true;
//                    MOBBW.onBackPressed();
                    MOBBW.powerOff();
                    MSKIN.powerOff();
                    MAPP.startTaskService(false);
//                    MSKIN.startStopPlaySongService(false);
                    MSKIN.stopPlayer();
                    MOBBW.startStopWorksLoadService(false);

                    MPAGE.mPageCurrent.onFinish();
                    MPAGE.mPageCurrent = null;              // 请注意，有些机型从这里退出后，一些全局变量没有被清除，需要在这里手动清除
                    this.finish();
                    System.exit(0);
                }
                mBackPressedTime = 0;
            }
        }else {
            MPAGE.mPageCurrent.onFinish();
        }
    }
    private void onTimer(){
        if (isStertPage) {
            isStertPage = false;
            MLOG(String.format("MRAM.gsFilePath %s", MRAM.gsFilePath));
            stertPage();
            initData();
            return;
        }
        if (!MAPP.openAarPage) {              // 没有打开SKIN或者OBB库的页面，使用线程后台的pollingTimer，需要跳过mMyTools
            if (MAPI.mMyTools != null && MAPI.mMyWorks != null) {
                MAPI.mMyTools.pollingTimer();
//                                MAPI.mMyWorks.pollingTimer();
                int newEvent = MAPI.mMyWorks.mSvrWorks.pollingEvent();
                if (newEvent > 0) {
                    if ((newEvent & WORKS_EVENT_DATA_REFRESH) > 0) {
                        MAPI.mMyWorks.mSvrWorks.eventDataRefresh();
                    }
//                    if ((newEvent & WORKS_EVENT_DATA_NEED_REFRESH) > 0) {
//                        MAPI.mMyWorks.mSvrWorks.eventDataNeedRefresh();
//                    }
                    MAPI.mMyWorks.sendUiEvent(0x00000000, false, "ok");
                } else if (MAPI.mMyWorks.isEventDataRefresh) {
//                MLOG("AddTaskPageA isEventDataRefresh");
                    MAPI.mMyWorks.sendUiEvent(0x00000000, false, "ok");
                }
            }
        }else {                                     // // 打开SKIN或者OBB库的页面，需要使用 MSKIN.onTimer();
             MSKIN.onTimer();
        }

        if ((System.currentTimeMillis() - gSecond) > (1 * 1000) ) {     // 1秒钟
            gSecond = System.currentTimeMillis();
            if (MAPP.mKcNoneListener != null){
                MAPP.mKcNoneListener.onMessage();
            }
            if (++gMinute > 3) {       // 30秒
                gMinute = 0;
                if (MAPP.mRunStatePage != null){
                    MAPP.mRunStatePage.onMessage();
                }
//                else {
//                    MAPP.makeBUsage();
//                }
            }

        }
//        if (MRAM.mTaskSysUpdate != null && MRAM.mTaskSysUpdate.checkBusy()) {
//            MSTRING(String.format("TaskSysUpdateA:%d%% file:%s", MRAM.mTaskSysUpdate.getPercent(), MRAM.mTaskSysUpdate.getFileName()));
//        }
        KcAdvs.systemOnTimer(300);

        if (gUserID != MSKIN.getCurrentUserID()) {
            MessageDbs messageDbs = new MessageDbs();
            messageDbs.getTopMessage(MSKIN.getCurrentUserID(), true);
            gUserID = MSKIN.getCurrentUserID();
        }
    }

    private void stertPage(){
//        setBasePage(this, (RelativeLayout) findViewById(R.id.rlPage));
        MPAGE.mPageActivity = this;
        MPAGE.mPageGroup = findViewById(R.id.rlPage);

        if (MPAGE.mPageCurrent == null) {
            MSTRING(String.format("PageActivity startPageMain A"));
            MPAGE.startBasePage(new MainPage());
        }else {
            MSTRING(String.format("PageActivity startPageMain B", MPAGE.mPageCurrent.getClass().getName()));
            if (MAPP.isChangThemeStyle){       // 更换主题
                MAPP.isChangThemeStyle = false;
                MPAGE.mPageList = null;
                MPAGE.mPageCurrent = null;
                MPAGE.startBasePage(new MainPage());
            }else {
                MPAGE.setInitView(MPAGE.mPageCurrent);
            }
        }
    }

    private void initData() {
        mMyTools.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message){
                if (methodType == 0){
                    MessageDbs messageDbs = new MessageDbs();
                    messageDbs.setToolsEvent();
                }
            }
        });

        mMyUtils.startRemoteServer(new cjmkcs.MessageListener() {
            @Override
            public boolean messageReceived(int max, int total, int offset, int extrTyp, int cmdTyp, String mixText, String extrText, int index) {
                // 这里需要返回byte[]给 服务器
                if (VARIA.mTaskRemoteServer == null){
                    VARIA.mTaskRemoteServer = new TaskRemoteServer();
                }
                return VARIA.mTaskRemoteServer.startTask((byte)(max & 0xff), (byte)(total & 0xff), (byte)(offset & 0xff), (byte) (extrTyp & 0xff), (byte) (cmdTyp & 0xff), mixText, (byte)(index & 0xff));
            }
        });

    }


}
